/// CreateTime 2020/4/21 10:53
/// CreateUser chen 
/// ProjectName tatoxApp

import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

import 'package:flutter_elf/config/component_index.dart';
import 'package:flutter_luban/flutter_luban.dart';
import 'package:path_provider/path_provider.dart';

class ImageUtils{
  static String getImageBase64(File image) {
    var bytes = image.readAsBytesSync();
    var base64 = base64Encode(bytes);
    return base64;
  }

  static File getImageFile(String base64) {
    var bytes = base64Decode(base64);
    return File.fromRawPath(bytes);
  }

  static Uint8List getImageByte(String base64) {
    return base64Decode(base64);
  }

  static const RollupSize_Units = ["GB", "MB", "KB", "B"];

  static String getRollupSize(int size) {
    int idx = 3;
    int r1 = 0;
    String result = "";
    while (idx >= 0) {
      int s1 = size % 1024;
      size = size >> 10;
      if (size == 0 || idx == 0) {
        r1 = (r1 * 100) ~/ 1024;
        if (r1 > 0) {
          if (r1 >= 10)
            result = "$s1.$r1${RollupSize_Units[idx]}";
          else
            result = "$s1.0$r1${RollupSize_Units[idx]}";
        } else
          result = s1.toString() + RollupSize_Units[idx];
        break;
      }
      r1 = s1;
      idx--;
    }
    return result;
  }


  //循环压缩
  static Future<String> loopCompress(File imageFile,{int lengthLimit = 200000})async{
    int length = imageFile.lengthSync();
    int compressCount = 1;
    while(length > lengthLimit){
      String newPath = await compressImage(imageFile);
      imageFile = new File(newPath);
      length = imageFile.lengthSync();
      globalPrint('第$compressCount次压缩');
      compressCount ++;
    }
    globalPrint('压缩后的文件大小是 ==== > ' + length.toString());
    globalPrint('压缩后的文件路径是 ==== > ' + imageFile.path);
    return imageFile.path;
  }

  static Future<String> compressImage(File imageFile)async{
    int length = imageFile.lengthSync();
    globalPrint(length.toString());
    if (imageFile == null) return null;
    final tempDir = await getTemporaryDirectory();
    CompressObject compressObject = CompressObject(
      imageFile:imageFile, //image
      path:tempDir.path, //compress to path
      quality: 85,//first compress quality, default 80
      step: 8,//compress quality step, The bigger the fast, Smaller is more accurate, default 6
//      mode: CompressMode.LARGE2SMALL,//default AUTO
    );
    String path = await Luban.compressImage(compressObject);
    return path;
  }

}